import { clsxm } from "shared/helpers";
import { Tooltip } from "shared/components";
import { useAtom, useAtomValue } from "jotai";
import { AnimatePresence, m } from "framer-motion";
import { useCallback, useEffect, useRef, useState } from "react";
import { allYearsAtom, selectYearAtom } from "@/store/years";
import CaretLeftIcon from "@/assets/icons/caret-left.svg?jsx";
import CaretRightIcon from "@/assets/icons/caret-right.svg?jsx";
import ArrowDownIcon from "@/assets/icons/arrow-down.svg?jsx";
import { IEventItem } from "@/lib/types";
import { EventTypeColorMaps } from "@/lib/constants";
import event from "@/lib/event";
import TriangleIcon from "@/assets/icons/triangle.svg?jsx";

enum Scrollable {
  Scroll = 0,
  ToLeft = 1,
  ToRight = 2,
  Disable = 3,
}
export default function HorizontalTime() {
  const allYears = useAtomValue(allYearsAtom);
  const [selectYear, setSelectYear] = useAtom(selectYearAtom);
  const scrollElRef = useRef<HTMLDivElement>(null);
  const [scrollReach, setScrollReach] = useState<Scrollable>(
    Scrollable.Disable,
  );

  const handleClickScroll = useCallback((direction: 1 | -1) => {
    const { scrollLeft, clientWidth, scrollWidth } = scrollElRef.current;
    if (clientWidth === scrollWidth) {
      setScrollReach(Scrollable.Disable);
      return;
    }
    const newPosition = scrollLeft + direction * 400;
    setScrollReach(
      newPosition <= 0
        ? Scrollable.ToRight
        : newPosition >= scrollWidth - clientWidth
          ? Scrollable.ToLeft
          : Scrollable.Scroll,
    );
    scrollElRef.current.scroll({
      left: newPosition,
      behavior: "smooth",
    });
  }, []);

  const handleScrollYearIntoView = useCallback((raw: string) => {
    const node = document.getElementById(raw);
    if (node) {
      node.scrollIntoView({
        behavior: "smooth",
        inline: "center",
        block: "nearest",
      });
    }
  }, []);

  useEffect(() => {
    const box = scrollElRef.current;
    function checkCanScroll() {
      const { scrollLeft, clientWidth, scrollWidth } = box;
      if (clientWidth === scrollWidth) {
        setScrollReach(Scrollable.Disable);
        return;
      }
      setScrollReach(
        scrollLeft === 0
          ? Scrollable.ToRight
          : // fixme: 总会有点误差，更好的解决办法？
            Math.abs(scrollLeft - (scrollWidth - clientWidth)) < 1
            ? Scrollable.ToLeft
            : Scrollable.Scroll,
      );
    }
    event.on("scrollYearIntoView", handleScrollYearIntoView);
    box.addEventListener("scrollend", checkCanScroll);
    const observer = new ResizeObserver(() => {
      checkCanScroll();
    });
    observer.observe(box);
    return () => {
      event.off("scrollYearIntoView", handleScrollYearIntoView);
      box.removeEventListener("scrollend", checkCanScroll);
      observer.disconnect();
    };
  }, [handleScrollYearIntoView]);

  return (
    <div className="flex bg-[#077077]/[0.07] px-4 pt-4">
      <button
        className={clsxm(
          "mb-4 flex-none text-[#0B9682]",
          scrollReach === Scrollable.ToRight && "text-opacity-50",
        )}
        onClick={() => handleClickScroll(-1)}
        disabled={scrollReach === Scrollable.ToRight}
      >
        <CaretLeftIcon />
      </button>
      <div
        className="flex min-w-0 flex-auto overflow-hidden pb-3 text-[10px]"
        ref={scrollElRef}
      >
        {allYears.map((year) => (
          <button
            key={year.gy_year}
            id={year.raw}
            className={clsxm(
              "relative h-6 w-10 flex-none whitespace-nowrap text-center text-[#4C9571] transition-all duration-200",
              selectYear === year.raw && "text-[14px] font-bold text-[#077741]",
            )}
            onClick={() => {
              setSelectYear(year.raw);
              handleScrollYearIntoView(year.raw);
            }}
          >
            <span>{year.gy_year.match(/\d+/)[0]}</span>
            <span className="absolute left-1/2 top-full -translate-x-1/2">
              {selectYear === year.raw ? (
                <TriangleIcon height={12} width={12} />
              ) : (
                <i
                  className={clsxm(
                    "block h-2 w-px bg-current transition-all duration-200 after:absolute after:-bottom-[14px] after:-translate-x-1/2 after:border-x-[6px] after:border-y-[14px] after:border-transparent",
                  )}
                />
              )}
            </span>
          </button>
        ))}
      </div>
      <button
        className={clsxm(
          "mb-4 flex-none text-[#0B9682]",
          scrollReach === Scrollable.ToLeft && "text-opacity-50",
        )}
        onClick={() => handleClickScroll(1)}
        disabled={scrollReach === Scrollable.ToLeft}
      >
        <CaretRightIcon />
      </button>
    </div>
  );
}
